package com.tancire.quartz.task;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.utils.StringUtils;
import com.tancire.net.domain.*;
import com.tancire.net.service.*;
import com.tancire.system.domain.SysTodayAmount;
import com.tancire.system.service.ISysTodayAmountService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 商品定时任务
 *
 * @author chenchao
 */
@Component("reportTask")
public class ReportTask {

    @Resource
    private IShopGoodsService shopGoodsService;

    @Resource
    private ICrmCompanyService crmCompanyService;

    @Resource
    private ICrmCompanyTaskService crmCompanyTaskService;

    @Resource
    private IAuthLogService authLogService;

    @Resource
    private ICrmCompanyIncomeService crmCompanyIncomeService;

    @Resource
    private ICrmCompanyIncomeDetailService crmCompanyIncomeDetailService;

    @Resource
    private ICrmCompanyPurseService crmCompanyPurseService;

    @Resource
    private ISysTodayAmountService sysTodayAmountService;

    @Resource
    private IShopTaskService shopTaskService;

    @Resource
    private RedisCache redisCache;

    /**
     * 定时同步客户收益数据
     */
    public void asyncCompanyIncome() {
        CrmCompany companyQuery = new CrmCompany();
        List<CrmCompany> companyList = this.crmCompanyService.selectCrmCompanyList(companyQuery);
        if (ObjectUtil.isNotEmpty(companyList)) {
            // 循环处理
            for (CrmCompany item : companyList) {
                this.asyncCompany(item);
            }
        }
    }

    /**
     * 处理单个客户的
     *
     * @param item
     */
    private void asyncCompany(CrmCompany item) {
        // 客户ID
        Long id = item.getId();
        // 初始化收益数据
        CrmCompanyIncome queryIncome = new CrmCompanyIncome();
        queryIncome.setCompanyId(id);
        String today = this.getToday("yyyy-MM-dd");
        String startTime = this.getYesterday(0);
        String endTime = this.getYesterday(1);
        queryIncome.setSettlementDate(today);
        List<CrmCompanyIncome> crmCompanyIncomeList = this.crmCompanyIncomeService.selectCrmCompanyIncomeList(queryIncome);
        // 初始化昨日收益主表
        CrmCompanyIncome income = new CrmCompanyIncome();
        Date current = new Date();
        BigDecimal incomeTotalAmount = BigDecimal.ZERO;
        if (ObjectUtil.isNotEmpty(crmCompanyIncomeList)) {
            income = crmCompanyIncomeList.get(0);
        } else {
            // 初始化数据
            income.setId(IdUtil.getSnowflakeNextId());
            income.setCompanyId(id);
            income.setCompanyName(item.getCustomerName());
            // 收益金额暂时为零
            income.setIncomeAmount(BigDecimal.ZERO);
            income.setSettlementDate(today);
            income.setSettlementTime(current);
            income.setCreateTime(current);
            this.crmCompanyIncomeService.insertCrmCompanyIncome(income);
        }

        // 查询今日收益
        SysTodayAmount queryTodayIncome = new SysTodayAmount();
        queryTodayIncome.setIncomeDay(today);
        List<SysTodayAmount> sysTodayAmounts = this.sysTodayAmountService.selectSysTodayAmountList(queryTodayIncome);
        SysTodayAmount sysTodayAmount = new SysTodayAmount();
        if (ObjectUtil.isNotEmpty(sysTodayAmounts)) {
            sysTodayAmount = sysTodayAmounts.get(0);
        }
        // 获取今日总积分
        BigDecimal allPoints = this.authLogService.selectYesterdayAuthTotal(startTime, endTime);

        // 查询推广的资源
        CrmCompanyTask queryTask = new CrmCompanyTask();
        queryTask.setCompanyId(id);
        List<CrmCompanyTask> companyTaskList = this.crmCompanyTaskService.selectCrmCompanyTaskList(queryTask);
        if (ObjectUtil.isNotEmpty(companyTaskList)) {
            List<CrmCompanyIncomeDetail> detailList = new ArrayList<>();
            int totalCount = 0;
            BigDecimal totalPoints = BigDecimal.ZERO;
            // 循环获取每个资源的下载量
            for (CrmCompanyTask task : companyTaskList) {
                // 查询资源激活量 前一天的，今天未过完，无法统计
                Long authId = task.getAuthId();
                List<AuthLog> authLogList = this.authLogService.selectAuthListBySourceId(authId, startTime, endTime);
                if (ObjectUtil.isNotEmpty(authLogList)) {
                    // 有日志说明有激活量 先删除之前的数据 防止数据重复
                    this.crmCompanyIncomeDetailService.deleteByTaskId(income.getId());
                    // 初始化收益明细数据
                    CrmCompanyIncomeDetail incomeDetail = new CrmCompanyIncomeDetail();
                    incomeDetail.setId(IdUtil.getSnowflakeNextId());
                    incomeDetail.setTaskId(income.getId());
                    incomeDetail.setCompanyId(id);
                    incomeDetail.setCompanyName(item.getCustomerName());
                    incomeDetail.setActiveCount(authLogList.size());
                    BigDecimal total = BigDecimal.ZERO;
                    for (AuthLog authLog : authLogList) {
                        BigDecimal authPrice = authLog.getAuthPrice();
                        if (null != authPrice) {
                            total = total.add(authPrice);
                        }
                    }
                    incomeDetail.setUsePoints(total);
                    incomeDetail.setIncomeAmount(BigDecimal.ZERO);
                    incomeDetail.setSettlementDate(today);
                    incomeDetail.setSourceId(authId);
                    incomeDetail.setSourceCode(task.getAuthCode());
                    incomeDetail.setSourceName(task.getAuthName());
                    incomeDetail.setCreateTime(current);
                    // 保存明细
                    detailList.add(incomeDetail);
                    totalCount = totalCount + incomeDetail.getActiveCount();
                    // 统计积分
                    totalPoints = totalPoints.add(total);
                    // 获取单价
                    BigDecimal unitPrice = this.getUnitPrice(task, sysTodayAmount.getIncomeAmount(), allPoints);
                    BigDecimal incomePrice = unitPrice.multiply(total).setScale(2, BigDecimal.ROUND_DOWN);
                    incomeDetail.setIncomeAmount(incomePrice);
                    incomeTotalAmount = incomeTotalAmount.add(incomePrice);
                    this.crmCompanyIncomeDetailService.insertCrmCompanyIncomeDetail(incomeDetail);
                }
            }
            // 汇总数据
            CrmCompanyPurse crmCompanyPurse = this.crmCompanyPurseService.selectCrmCompanyPurseByCompanyId(id);
            // 0表示需要更新 1 表示保存
            int saveFlag = 0;
            if (null == crmCompanyPurse || null == crmCompanyPurse.getId()) {
                crmCompanyPurse = new CrmCompanyPurse();
                crmCompanyPurse.setId(IdUtil.getSnowflakeNextId());
                crmCompanyPurse.setCompanyId(item.getId());
                crmCompanyPurse.setCompanyName(item.getCustomerName());
                crmCompanyPurse.setTodayAmount(BigDecimal.ZERO);
                crmCompanyPurse.setTotalAmount(BigDecimal.ZERO);
                crmCompanyPurse.setWithdrawPrice(BigDecimal.ZERO);
                crmCompanyPurse.setTotalCount(0);
                crmCompanyPurse.setCreateTime(new Date());
                saveFlag = 0;
            } else {
                saveFlag = 1;
                Date updateTime = crmCompanyPurse.getUpdateTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String upDate = sdf.format(updateTime);
                String curDate = sdf.format(new Date());
                if (upDate.equals(curDate)) {
                    // 需要清数量
                    Integer todayCount = crmCompanyPurse.getTodayCount();
                    Integer allCount = crmCompanyPurse.getTotalCount();
                    if (null != allCount && allCount > 0) {
                        if (null == todayCount) {
                            todayCount = 0;
                        }
                        allCount = allCount - todayCount;
                        crmCompanyPurse.setTotalCount(allCount);
                    }
                    // 清金额
                    BigDecimal todayAmount = crmCompanyPurse.getTodayAmount();
                    BigDecimal allAmount = crmCompanyPurse.getTotalAmount();
                    if (null != allAmount && allAmount.compareTo(BigDecimal.ZERO) > 0) {
                        if (null == todayAmount) {
                            todayAmount = BigDecimal.ZERO;
                        }
                        allAmount = allAmount.subtract(todayAmount);
                        crmCompanyPurse.setTotalAmount(allAmount);
                    }
                }
            }
            // 更新主表预估收益
            income.setIncomeAmount(incomeTotalAmount);
            this.crmCompanyIncomeService.updateIncomeAmount(income);

            // 初始化数据
            crmCompanyPurse.setTodayAmount(BigDecimal.ZERO);
            crmCompanyPurse.setTodayCount(0);
            // 统计数量
            crmCompanyPurse.setTodayCount(totalCount);
            Integer hisTotalCount = crmCompanyPurse.getTotalCount();
            if (null == hisTotalCount) {
                hisTotalCount = 0;
            }
            hisTotalCount = hisTotalCount + totalCount;
            crmCompanyPurse.setTotalCount(hisTotalCount);
            // 设置今日预估收益
            crmCompanyPurse.setTodayAmount(incomeTotalAmount);
            BigDecimal allAmount = crmCompanyPurse.getTotalAmount();
            allAmount = allAmount.add(incomeTotalAmount);
            crmCompanyPurse.setTotalAmount(allAmount);

            // 保存数据
            if (saveFlag == 0) {
                this.crmCompanyPurseService.insertCrmCompanyPurse(crmCompanyPurse);
            } else {
                this.crmCompanyPurseService.updateCrmCompanyPurse(crmCompanyPurse);
            }
        }
    }

    private BigDecimal getUnitPrice(CrmCompanyTask task, BigDecimal todayAmount, BigDecimal allPoints) {
        if (null != allPoints && allPoints.compareTo(BigDecimal.ZERO) > 0) {
            // 计算出单价
            BigDecimal unitPrice = todayAmount.divide(allPoints, 2, BigDecimal.ROUND_DOWN);
            ShopTask shopTask = shopTaskService.selectShopTaskById(task.getShopTaskId());
            if (null == shopTask) {
                shopTask = new ShopTask();
            }
            BigDecimal authRate = shopTask.getAuthRate();
            if (null == authRate) {
                authRate = BigDecimal.ZERO;
            }
            unitPrice = unitPrice.multiply(authRate).setScale(2, BigDecimal.ROUND_DOWN);
            return unitPrice;
        }
        return BigDecimal.ZERO;
    }

    private String getYesterday(int flag) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        // 设置日期为前一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String format = sdf.format(calendar.getTime());
        if (flag == 0) {
            format = format + " 00:00:00";
        } else {
            format = format + " 23:59:59";
        }
        return format;
    }

    private String getToday(String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date());
    }

    /**
     * 转Int
     *
     * @param cacheObject
     * @return
     */
    private int convertToInt(Object cacheObject) {
        if (null == cacheObject) {
            return 0;
        }
        try {
            return Integer.parseInt((String) cacheObject);
        } catch (Exception e) {
            // 不处理
        }
        return 0;
    }
}
